import { create } from 'zustand';
import { persist, devtools } from 'zustand/middleware';
import { mountStoreDevtool } from 'simple-zustand-devtools';
import Taro from '@tarojs/taro';
import { reLaunch } from '@/utils/router';

interface UserState {
  logined: boolean;
  token: string;
  data: {
    id: any;
    name: any;
  };
}
interface UserAction {
  doLogin: ({ username, password }) => Promise<void>;
  doLogout: () => Promise<void>;
}

/** 用户数据store */
const useUserStore = create(
  devtools<UserState & UserAction>(
    (set, get) => ({
      logined: false,
      token: '',
      data: {
        id: '',
        name: '',
      },
      doLogin: async ({ username, password }) => {
        Taro.showLoading({
          mask: true,
          title: '正在登录',
        });
        // TODO 调接口
        Taro.hideLoading();

        set({
          logined: true,
          token: 'TODO',
          data: {
            id: 'TODO',
            name: 'TODO',
          },
        });

        // 跳转首页
        reLaunch({ url: '/pages/index/index' });
      },
      doLogout: async () => {
        // TODO 调接口
        set({
          logined: false,
          token: '',
          data: {
            id: '',
            name: '',
          },
        });
        reLaunch({ url: '/pages/Login/index' });
      },
    }),
    {
      store: 'useUserStore',
    },
  ),
);

export default useUserStore;

if (process.env.NODE_ENV === 'development') {
  mountStoreDevtool('useUserStore', useUserStore);
}
